package fr.afcepf.atod18.fw.controler;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import fr.afcepf.atod18.fw.form.IActionForm;



public class MyBeanPopulate {
	
	static void populateBean(IActionForm actionForm, Map params) {
		Class c = actionForm.getClass();
		Set<Entry> entrySet = params.entrySet();
		for(Entry entry : entrySet) {
			String ligneSaisie = "";
			String[] saisie = (String[]) entry.getValue();
			for(int i = 0; i < saisie.length; i++) {
				ligneSaisie += saisie[i];
			}
			System.out.println("MyBeanPopulate entry : " + entry.getKey() + "=" + ligneSaisie);
			
			// Reconstitution getter setter
            String cle = entry.getKey().toString();
            String firstLettre = cle.substring(0, 1).toUpperCase();
            String setMethodName = "set"+firstLettre+ cle.substring(1,cle.length());
            String getMethodName = "get"+firstLettre+ cle.substring(1,cle.length());
            System.out.println("cle=" + cle + " setter=" + setMethodName + " getter=" + getMethodName);
			
            Method methode = null;
			try {
				// mettre la valeur saisie dans l'attribut
				methode = c.getMethod(setMethodName, new Class[] { String.class });
				methode.invoke(actionForm, new Object[] { saisie[0] });
		        System.out.println("methode = " + methode.toString());

		        methode = c.getMethod(getMethodName, null);
				String texte = (String) methode.invoke(actionForm, null);
		        System.out.println("texte saisi = " + texte);
			} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
				e.printStackTrace();
			}
            
		}
	}

}
